import axios from "axios";
import { showLoading, hideLoading } from "./loading";
import type { Result } from "../types/api";
import storage from "./storage";
import { message } from "./AntdGlobal";

//创建一个实例
const instance = axios.create({
    timeout: 8000,
    timeoutErrorMessage: '您的请求超时',
    withCredentials: true,
    headers: {
        icode: '11E0EEDC543C1BC7'
    }
})

instance.interceptors.request.use((config) => {
    if (config.showLoading) showLoading()
    const token = storage.get('token')
    if (token) {
        config.headers.Authorization = 'Bearer ' + token
    }
    // config.baseURL = 'http://api-driver.marsview.com.cn'
    return { ...config }
}, (error) => {
    return Promise.reject(error);
})

instance.interceptors.response.use((response) => {
    hideLoading()
    if (response.config.responseType === 'blob') return response
    const data: Result = response.data
    if (data.code == 500001) {
        message.error(data.msg)
        storage.remove('token')
        location.href = '/login?callback=' + encodeURIComponent(location.href)
    } else if (data.code != 0) {
        if (!response.config.showError) {
            return Promise.resolve(data)
        } else {
            message.error(data.msg)
            return Promise.reject(data)
        }
    }
    return data.data
}, error => {
    hideLoading()
    return Promise.reject(error)
})

interface IConfig {
    showLoading?: boolean,
    showError?: boolean
}

export default {
    get<T>(url: string, params?: any, options: IConfig = { showLoading: true, showError: true }): Promise<T> {
        return instance.get(url, { params, ...options })
    },
    post(url: string, params?: any, options: IConfig = { showLoading: true, showError: true }) {
        return instance.post(url, params, options)
    },
    downLoad(url: string, data: any, fileName = 'fileName.xlsx') {
        instance({
            url,
            data,
            method: 'post',
            responseType: 'blob'
        }).then(response => {
            const blob = new Blob([response.data], {
                type: response.data.type
            })
            const name = response.headers['file-name'] as string || fileName
            const link = document.createElement('a')
            link.download = decodeURIComponent(name)
            link.href = URL.createObjectURL(blob)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(link.href)
        })
    }
}
